package org.shock.ss.sms.commons.db;

import java.sql.*;

import org.apache.log4j.*;

/**
 * Proxool连接池工具类，用于connection管理和事物管理器的获得
 * 
 */
public class ProxoolDbPool {
	/** 用来把Connection绑定到当前线程上的变量 */
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

	private static Logger log = Logger.getLogger(ProxoolDbPool.class);

	/** 获得连接 */
	public static Connection getConnection() throws Exception {
		Connection conn = tl.get(); // 先从当前线程上取出连接实例
		if (null == conn || conn.isClosed()) { // 如果当前线程上没有Connection的实例
			try {
				conn = DriverManager.getConnection("proxool.MyPool"); // 从连接池中取出一个连接实例
				tl.set(conn); // 把连接绑定到当前线程上
			} catch (Exception e) {
				System.out.println("====="+e);
				e.printStackTrace();
				log.debug(e, e);
				throw e;
			}
		}
		if (conn.isClosed()) {// 如果连接已关闭
			// 有时proxool会自动关闭连接，但线程中连接未移除，此时重新绑定conn到线程
			conn = DriverManager.getConnection("proxool.MyPool"); // 从连接池中取出一个连接实例
			tl.set(conn);
		}
		log.debug("获得连接：" + conn);
		return conn;
	}

	/** 获得连接 */
	public static Connection getConnection(Boolean flg) throws Exception {
		Connection conn = DriverManager.getConnection("proxool.MyPool"); // 从连接池中取出一个连接实例
		log.debug("获得连接：" + conn);
		return conn;
	}

	/**
	 * 根据传入的对象来关闭对象
	 * 
	 * @param objs
	 *            不定长参数
	 */
	public static void close(Object... objs) throws Throwable {
		try {
			for (Object obj : objs) {
				if (obj instanceof PreparedStatement) {
					PreparedStatement ps = (PreparedStatement) obj;
					ps.close();
				} else if (obj instanceof Statement) {
					Statement st = (Statement) obj;
					st.close();
				} else if (obj instanceof ResultSet) {
					ResultSet rs = (ResultSet) obj;
					rs.close();
				} else if (obj instanceof Connection) {
					Connection conn = (Connection) obj;
					conn.close();
				} else {
					throw new SQLException(obj + "不是可关闭的对象！");
				}
			}
		} catch (SQLException e) {
			log.debug(e, e);
			throw e;
		}
	}

	/** 关闭连接 */
	public static void closeConnection(Connection conn) {
		if (conn == null)
			return;
		try {
			tl.remove();//
			conn.close();
			log.debug("连接关闭：" + conn);
		} catch (Exception e) {
			log.debug(e, e);
		}
	}

	/** 关闭连接Statement */
	public static void closeStatement(Statement stmt) {
		if (stmt == null)
			return;
		try {
			stmt.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** 关闭连接ResultSet */
	public static void closeResultSet(ResultSet rs) {
		if (rs == null)
			return;
		try {
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/** 获得事务管理器 */
	public static TransactionManager getTranManager() throws Exception {
		return new TransactionManager(getConnection());
	}

}
